<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { useMerchantStore } from "@/store";
import { ElMessage, ElMessageBox } from "element-plus";
import MerchantLayout from "@/components/merchant/MerchantLayout.vue";

const merchantStore = useMerchantStore();
const promotions = ref<any[]>([]);
const loading = ref(false);

// 促销表单
const promotionForm = reactive({
  id: "",
  name: "",
  type: "折扣",
  discount: 0,
  minAmount: 0,
  startTime: "",
  endTime: "",
  description: "",
});
const promotionDialogVisible = ref(false);
const isEdit = ref(false);
const formLoading = ref(false);

// 促销类型选项
const promotionTypes = [
  { label: "折扣", value: "折扣" },
  { label: "满减", value: "满减" },
  { label: "赠品", value: "赠品" },
];

// 获取促销列表
const fetchPromotions = async () => {
  if (!merchantStore.currentStoreId) {
    promotions.value = [];
    return;
  }

  loading.value = true;
  try {
    const { listPromotions } = await import("@/api/index");
    const promoRes = await listPromotions(merchantStore.currentStoreId);
    const promo = promoRes.data?.data || promoRes.data;
    promotions.value = Array.isArray(promo) ? promo : promo?.list || [];
  } catch (error) {
    console.error("获取促销列表失败", error);
    ElMessage.error("获取促销列表失败");
  } finally {
    loading.value = false;
  }
};

// 打开添加促销对话框
const openAddPromotion = () => {
  isEdit.value = false;
  Object.assign(promotionForm, {
    id: "",
    name: "",
    type: "折扣",
    discount: 0,
    minAmount: 0,
    startTime: "",
    endTime: "",
    description: "",
  });
  promotionDialogVisible.value = true;
};

// 打开编辑促销对话框
const openEditPromotion = (row: any) => {
  isEdit.value = true;
  Object.assign(promotionForm, row);
  promotionDialogVisible.value = true;
};

// 保存促销
const handleSavePromotion = async () => {
  if (!promotionForm.name) {
    ElMessage.warning("请输入促销名称");
    return;
  }

  formLoading.value = true;
  try {
    if (isEdit.value) {
      // 更新促销
      const { updatePromotion } = await import("@/api/index");
      await updatePromotion(
        merchantStore.currentStoreId,
        promotionForm.id,
        promotionForm
      );
      ElMessage.success("促销更新成功");
    } else {
      // 添加促销
      const { createPromotion } = await import("@/api/index");
      await createPromotion(merchantStore.currentStoreId, promotionForm);
      ElMessage.success("促销添加成功");
    }
    promotionDialogVisible.value = false;
    fetchPromotions();
  } catch (error) {
    console.error("保存促销失败", error);
    ElMessage.error("操作失败");
  } finally {
    formLoading.value = false;
  }
};

// 删除促销
const handleDeletePromotion = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除该促销活动吗？删除后无法恢复",
      "提示",
      {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    );

    loading.value = true;
    const { deletePromotion } = await import("@/api/index");
    await deletePromotion(merchantStore.currentStoreId, row.id);
    ElMessage.success("促销已删除");
    fetchPromotions();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除促销失败", error);
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

onMounted(async () => {
  // 确保店铺信息已加载
  if (merchantStore.stores.length === 0) {
    await merchantStore.fetchStores();
  }

  // 获取促销列表
  await fetchPromotions();
});

// 监听店铺变化
watch(() => merchantStore.currentStoreId, fetchPromotions);
</script>

<template>
  <merchant-layout>
    <div class="promotions-view">
      <el-card class="promotions-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>促销管理</span>
            <el-button
              type="primary"
              size="small"
              @click="openAddPromotion"
              :disabled="!merchantStore.currentStoreId"
            >
              添加促销
            </el-button>
          </div>
        </template>

        <div v-if="!merchantStore.currentStoreId" class="no-store-tip">
          <el-empty description="请先选择店铺" />
        </div>

        <el-table
          v-else
          :data="promotions"
          v-loading="loading"
          style="width: 100%"
          stripe
        >
          <el-table-column prop="name" label="活动名称" />
          <el-table-column prop="type" label="类型" />
          <el-table-column prop="startTime" label="开始时间" />
          <el-table-column prop="endTime" label="结束时间" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.status === '进行中'
                    ? 'success'
                    : scope.row.status === '已结束'
                    ? 'info'
                    : 'warning'
                "
              >
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button size="small" @click="openEditPromotion(row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDeletePromotion(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 促销编辑对话框 -->
      <el-dialog
        v-model="promotionDialogVisible"
        width="500px"
        :show-close="false"
      >
        <template #header>
          <div class="custom-dialog-header">
            <span>{{ isEdit ? "编辑促销" : "添加促销" }}</span>
            <button
              class="custom-close-btn"
              @click="promotionDialogVisible = false"
              aria-label="关闭"
            >
              <el-icon><Close /></el-icon>
            </button>
          </div>
        </template>
        <el-form :model="promotionForm" label-width="100px">
          <el-form-item label="促销名称">
            <el-input
              v-model="promotionForm.name"
              placeholder="请输入促销名称"
            />
          </el-form-item>
          <el-form-item label="促销类型">
            <el-select v-model="promotionForm.type" style="width: 100%">
              <el-option
                v-for="type in promotionTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>

          <template v-if="promotionForm.type === '折扣'">
            <el-form-item label="折扣力度">
              <el-input-number
                v-model="promotionForm.discount"
                :min="0"
                :max="10"
                :precision="1"
                :step="0.1"
                style="width: 100%"
              />
              <div class="form-tip">折扣值为0-10之间，例如：8.5表示8.5折</div>
            </el-form-item>
          </template>

          <template v-if="promotionForm.type === '满减'">
            <el-form-item label="满减金额">
              <el-input-number
                v-model="promotionForm.minAmount"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
              <div class="form-tip">订单满多少金额可使用此优惠</div>
            </el-form-item>
            <el-form-item label="优惠金额">
              <el-input-number
                v-model="promotionForm.discount"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </template>

          <el-form-item label="开始时间">
            <el-date-picker
              v-model="promotionForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="promotionForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="活动说明">
            <el-input
              v-model="promotionForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入活动说明"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="promotionDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSavePromotion"
            :loading="formLoading"
            >确定</el-button
          >
        </template>
      </el-dialog>
    </div>
  </merchant-layout>
</template>

<style scoped>
.promotions-view {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  height: 64px;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.store-selector {
  display: flex;
  align-items: center;
}

.store-selector .label {
  margin-right: 10px;
  color: #909399;
}

.el-main {
  padding: 20px;
}

.promotions-card {
  border-radius: 18px;
  background: #fffbe7;
  box-shadow: 0 2px 8px #ffd54f33;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.no-store-tip {
  padding: 30px 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
.custom-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  padding-right: 4px;
}
.custom-close-btn {
  border: none;
  background: #f5f6fa;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-left: 8px;
}
.custom-close-btn:hover {
  background: #ffd54f;
  color: #a05a1c;
  box-shadow: 0 4px 16px rgba(255, 213, 79, 0.15);
}
</style>
